package com.cwt_taxi_xa;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.cwt_taxi_xa.adapter.AdapterOnClickListener;
import com.cwt_taxi_xa.adapter.GridAdapter;
import com.cwt_taxi_xa.adapter.SettingItem;
import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.data.DataUtil;
import com.cwt_taxi_xa.protocol.DeviceBiz;
import com.cwt_taxi_xa.service.DvrService;
import com.cwt_taxi_xa.util.AppBiz;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.TTsFunction;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
/**
 * 设置类
 * @author ferch
 * @create_time 2014-3-20
 *
 */
public class Setting extends CWTBaseActivity implements OnTouchListener{

	private static final String TAG = "Setting";
	public TextView showtime;
	public static Handler handler;
	public static boolean updateTime;
	private AppBiz appBiz;

	private GridView gridview;
	private List<SettingItem>  dataList;
	private GridAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_function);

		setupViews();
		//addListener();

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 100){
					showtime.setText((String)msg.obj);
				}
				if(msg.what == 1001){
					showPbar();
				}
				if(msg.what == 1002){
					pBar.setProgress(dsize);
				}
				if(msg.what == 1003){
					pBar.dismiss();
				}
			}
		};
		appBiz = new AppBiz(this);
		initData();
	}

	private void setupViews() {
		// TODO Auto-generated method stub
		showtime = (TextView)findViewById(R.id.showtime);
		showtime.setVisibility(View.VISIBLE);
		showtime.setText("设备维护");

		gridview = (GridView) findViewById(R.id.gridview);
		gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
	}

	private void addListener() {
		// TODO Auto-generated method stub
		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
									long arg3) {
				// TODO Auto-generated method stub

			}
		});
	}


	private AdapterOnClickListener onClickIndustryChannel = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(Setting.this, IndustryChannelSetting.class));
		}
	};

	private AdapterOnClickListener onClickRecovery = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			doRecovery();
		}
	};


	private AdapterOnClickListener onClickFileManager = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			appBiz.launchApp("com.softwinner.TvdFileManager");
		}
	};


	private AdapterOnClickListener onClickDownloadData = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(Setting.this, DownloadData.class));
		}
	};

	private AdapterOnClickListener onClickSettings = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			appBiz.launchApp("com.android.settings");
		}
	};

	private AdapterOnClickListener onClickShutdown = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			try {
				Intent intent = new Intent(
						"android.intent.action.ACTION_REQUEST_SHUTDOWN");
				intent.putExtra("android.intent.extra.KEY_CONFIRM", true);
				// 其中false换成true,会弹出是否关机的确认窗口
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	};

	private AdapterOnClickListener onClickWriteCard = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			Intent intent = new Intent();
			intent.setClass(Setting.this, ActivityWriteCard.class);
			startActivity(intent);
			Setting.this.finish();
		}
	};

	private AdapterOnClickListener onClickSoftwinnerUpdate = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			new AppBiz(MainApplication.getInstance()).launchApp("com.softwinner.update");
		}
	};

	private AdapterOnClickListener onClickDVR = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			final int dvr = SPUtils.getParamInteger(SPConstants.SPK_dvr, SPConstants.SPV_dvr);

			AlertDialog.Builder normalDialog3 = new AlertDialog.Builder(Setting.this);
			normalDialog3.setTitle("提示");
			normalDialog3.setMessage("当前DVR厂家："+(dvr==1?"通立":"车务通")+"\n是否切换？\n非维护人员千万别操作！！！\n切换后重启设备，新系统（1月17日）会设置对应本地IP");
			normalDialog3.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(dvr==1){
						Toast.makeText(Setting.this, "启用车务通DVR", 1500).show();
						SPUtils.setParam(SPConstants.SPK_dvr, 2);
					}else{
						Toast.makeText(Setting.this, "启用通立DVR", 1500).show();
						SPUtils.setParam(SPConstants.SPK_dvr, 1);
					}
				}
			});
			normalDialog3.setNegativeButton("取消", null);
			normalDialog3.show();
		}
	};

	private AdapterOnClickListener onClickUnableEvaluation = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			if(SPUtils.getParamBoolean("pingjiaqiback", true)){
				SPUtils.setParam("pingjiaqiback", false);
				Toast.makeText(Setting.this, "禁用后排评价器", 1500).show();
			}else{
				SPUtils.setParam("pingjiaqiback", true);
				Toast.makeText(Setting.this, "打开后排评价器", 1500).show();
			}
		}
	};

	private AdapterOnClickListener onClickSystemApp = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(Setting.this, SystemAppActivity.class));
		}
	};

	private AdapterOnClickListener onClickJJQ = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(Setting.this, ActivityJJQ.class));
		}
	};

	private AdapterOnClickListener onClickFTP = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			AlertDialog.Builder normalDialog = new AlertDialog.Builder(Setting.this);
			normalDialog.setTitle("提示");
			normalDialog.setMessage("确定更新程序？");
			normalDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					new Thread(new Runnable() {
						@Override
						public void run() {
							doCheckFTP();
						}
					}).start();
				}
			});
			normalDialog.setNegativeButton("取消", null);
			normalDialog.show();
		}
	};

	private AdapterOnClickListener onClickMask = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			AlertDialog.Builder normalDialog = new AlertDialog.Builder(Setting.this);
			normalDialog.setTitle("提示");
			normalDialog.setMessage("确定关闭口罩识别？");
			normalDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					SPUtils.setParam(SPConstants.SPK_Mask,true);
					TTsFunction.speakText("口罩识别已开启");
				}
			});
			normalDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialogInterface, int i) {
					SPUtils.setParam(SPConstants.SPK_Mask,false);
					TTsFunction.speakText("口罩识别已关闭");
				}
			});
			normalDialog.show();
		}
	};

	private AdapterOnClickListener onClickFMConfig = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(Setting.this, ActivityFMConfig.class));
		}
	};

	private AdapterOnClickListener onClickMaskCamera = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(Setting.this, ActivitySelectMaskCamera.class));
		}
	};

	private AdapterOnClickListener onClickVolumeChannel = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(Setting.this, ActivityVolumeChannel.class));
		}
	};


	private AdapterOnClickListener onClickMeter= new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(Setting.this, ActivityMeter.class));
		}
	};

	private AdapterOnClickListener onClickVoice = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			startActivity(new Intent(Setting.this, ActivityVoice.class));
		}
	};

	//确定重启通立DVR,暂未使用
	private AdapterOnClickListener onClickRestartDvr = new AdapterOnClickListener() {
		@Override
		public void onItemClick(View view) {
			AlertDialog.Builder normalDialog2 = new AlertDialog.Builder(Setting.this);
			normalDialog2.setTitle("提示");
			normalDialog2.setMessage("确定重启通立DVR？");
			normalDialog2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					new Thread(new Runnable() {
						@Override
						public void run() {
							DvrService.getInstance().reStartTLDVR();
						}
					}).start();
				}
			});
			normalDialog2.setNegativeButton("取消", null);
			normalDialog2.show();
		}
	};

	private void initData() {
		// TODO Auto-generated method stub
		dataList = new ArrayList<>();

		dataList.add(new SettingItem("行业通道",R.drawable.ic_star,onClickIndustryChannel));
		dataList.add(new SettingItem("恢复出厂",R.drawable.ic_star,onClickRecovery));
		dataList.add(new SettingItem("文件管理",R.drawable.ic_star,onClickFileManager));

		dataList.add(new SettingItem("本地数据",R.drawable.ic_star,onClickDownloadData));
		dataList.add(new SettingItem("系统设置",R.drawable.ic_star,onClickSettings));
		dataList.add(new SettingItem("重启设备",R.drawable.ic_star,onClickShutdown));

		dataList.add(new SettingItem("写卡工具",R.drawable.ic_star,onClickWriteCard));
		dataList.add(new SettingItem("切换DVR",R.drawable.ic_star,onClickDVR));
		dataList.add(new SettingItem("评价器",R.drawable.ic_star,onClickUnableEvaluation));

		dataList.add(new SettingItem("软件拓展",R.drawable.ic_star,onClickSystemApp));
		dataList.add(new SettingItem("计价器",R.drawable.ic_star,onClickJJQ));
		dataList.add(new SettingItem("FTP",R.drawable.ic_star,onClickFTP));

		dataList.add(new SettingItem("系统升级",R.drawable.ic_star,onClickSoftwinnerUpdate));
		dataList.add(new SettingItem("收音参数",R.drawable.ic_star,onClickFMConfig));
		dataList.add(new SettingItem("音量调试",R.drawable.ic_star,onClickVolumeChannel));

		dataList.add(new SettingItem("计价计程",R.drawable.ic_star,onClickMeter));
		dataList.add(new SettingItem("语音评价测试",R.drawable.ic_star,onClickVoice));
		dataList.add(new SettingItem("开启口罩识别",R.drawable.ic_star,onClickMask));
		dataList.add(new SettingItem("口罩识别摄像头选择",R.drawable.ic_star,onClickMaskCamera));

		adapter = new GridAdapter(this,dataList);
		gridview.setAdapter(adapter);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateTime = true;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		updateTime = false;
	}

	private void doRecovery() {
		// TODO Auto-generated method stub
		Builder dialog = new AlertDialog.Builder(Setting.this);
		dialog.setTitle("恢复出厂").setIcon(android.R.drawable.ic_dialog_info)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
				/*SystemDataBiz.initSystemData();
				SystemDataBiz.recoveryData(Setting.this);
				SystemDataBiz.recoveryLauncherData(Setting.this);
				DispatchCenterUsers.stopComm(1);
				ImageLoader.getInstance().clearDiscCache();
				ImageLoader.getInstance().clearMemoryCache();
				NetworkHandler.showToastForCustom("恢复出厂成功！");*/
						DataUtil.saveJJQ(0);
						DeviceBiz.setDeviceCode(SPConstants.SPV_clientcode);
						DeviceBiz.setCarNumber(SPConstants.SPV_carcode);
						DeviceBiz.setCarNumberCorrection(true);
						DeviceBiz.setIp(SPConstants.SPV_ip);
						DeviceBiz.setIpBak(SPConstants.SPV_ip);
						DeviceBiz.setPort(SPConstants.SPV_PORT);
						DeviceBiz.setPortBak(SPConstants.SPV_PORT);
						DeviceBiz.setSwitcher(1);
						DeviceBiz.setSwitcherBak(1);
//				Intent intent = new Intent(
//						"android.intent.action.ACTION_REQUEST_SHUTDOWN");
//				intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
//				// 其中false换成true,会弹出是否关机的确认窗口
//				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//				startActivity(intent);
						dialog.dismiss();
						Toast.makeText(Setting.this, "恢复出厂成功！", 1000).show();
					}
				}).setMessage("恢复出厂后，用户数据将会还原！").setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		}).create().show();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return false;
	}
	/**
	 * 请求终端手机号
	 */
	/*public void sendPhoneRequest() {
		SendDateToSerial.witeSerialInfo(YXEncoder.getPhoneRequest());
	}*/

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub

	}











	private void doCheckFTP(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				FTPClient client = new FTPClient();
				try {

					client.connect("117.34.70.206", 21);//其中Host为Ftp地址，端口为固定的21
					// TODO
					client.login("taxiapk", "xiantaxi");
					final String[] file = client.listNames();
					//for (int i = 0; i < 1; i++) {
					for (int i = 0; i < file.length; i++) {
						final File file_down = new File(Constants.SDPath+"FtpApk_"+file[i]);
						if (file_down.exists()) {
							file_down.delete();
						}
						Log.i(TAG, "文件名：----->" + file[i]);
						if(client==null){
							break;
						}
						if(file[i]==null){
							break;
						}
						if(file[i].startsWith("xa_e5_")){
							Log.i(TAG, "download 文件名：----->" + file[i]);
							//第一个参数为ftp上的文件名，第二个参数为下载到本地后需要保存文件的名字，第三个为下载过程中的监听器
							client.download(file[i], file_down, new FTPDataTransferListener() {

								@Override
								public void transferred(int arg0) {
									//正在下载
									Log.i(TAG, "FTPDataTransferListener：----->transferred: "+arg0);
									dsize+=(arg0);
//									pBar.setProgress(dsize);
									handler.sendMessage(handler.obtainMessage(1002));
								}

								@Override
								public void started() {
									//开始下载
									Log.i(TAG, "FTPDataTransferListener：----->started");
									handler.sendMessage(handler.obtainMessage(1001));
								}

								@Override
								public void failed() {
									//下载失败
									Log.i(TAG, "FTPDataTransferListener：----->failed");
									try {
										Toast.makeText(Setting.this, "下载失败", 1000).show();
										pBar.dismiss();
									} catch (Exception e) {
									}
								}

								@Override
								public void completed() {
									//下载成功
									handler.sendMessage(handler.obtainMessage(1003));
									Log.i("TAG", "FTPDataTransferListener：----->completed");
									Intent intent = new Intent(Intent.ACTION_VIEW);
									intent.setDataAndType(Uri.fromFile(file_down), "application/vnd.android.package-archive");
									startActivity(intent);

								}

								@Override
								public void aborted() {
									//被取消
									Log.i(TAG, "FTPDataTransferListener：----->aborted");
									try {
										Toast.makeText(Setting.this, "取消下载", 1000).show();
										pBar.dismiss();
									} catch (Exception e) {
									}
								}
							});
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
					try {
						Toast.makeText(Setting.this, "下载出错", 1000).show();
						pBar.dismiss();
					} catch (Exception e1) {
					}
				}
			}
		}).start();
	}
	ProgressDialog pBar;
	int dsize;
	void showPbar(){
		pBar = new ProgressDialog(this);
		pBar.setCanceledOnTouchOutside(false);
		pBar.setTitle("正在下载");
		pBar.setMax(19365*1024);
		dsize = 0;
		pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//		pBar.setButton( DialogInterface.BUTTON_POSITIVE,"下载不动？ 刷新一下~"
//				,new DialogInterface.OnClickListener(){
//			  public void onClick(DialogInterface d, int i) {
//				  pBar.dismiss();
//				  doCheckFTP();
//			  }
//			}); 
		pBar.show();
	}






}
